﻿Shader "Normal"
{
    Properties
    {
        _BaseColor("Color",Color) = (1,1,1,1)
        _BaseMap("Texture",2D) = "white"{}
        [NoScaleOffset]_BumpMap("Normal Map",2D) = "bump" {}
        _BumpScale("NormalScale",Range(-1,1)) = 1
    }
    SubShader
    {
        Tags
        {
            "RenderPipeline"="UniversalRenderPipeline"
            "LightMode"="UniversalForward"
            "RenderType"="Opaque"
        }
        LOD 100

        HLSLINCLUDE
        #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
        #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl"

        TEXTURE2D(_BaseMap);    SAMPLER(sampler_BaseMap);
        TEXTURE2D(_BumpMap);    SAMPLER(sampler_BumpMap);

        CBUFFER_START(UnityPerMaterial)
        float4 _BaseMap_ST;
        half4 _BaseColor;
        half _BumpScale;
        CBUFFER_END
        ENDHLSL

        pass
        {
            HLSLPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            struct a2v
            {
                float4 positionOS : POSITION;
                float3 normalOS : NORMAL;
                float4 tangentOS : TANGENT;
                float2 texcoord : TEXCOORD;
            };

            struct v2f
            {
                float4 positionCS : SV_POSITION;
                float3 positionWS : TEXCOORD0;
                half3 normalWS : NORMAL;
                half3 tangent : TANGENT;
                half3 bitangent : TEXCOORD1;
                half2 texcoord : TEXCOORD2;
            };

            v2f vert(a2v v)
            {
                v2f o;
                VertexPositionInputs vertexInput = GetVertexPositionInputs(v.positionOS.xyz);
                o.positionCS = vertexInput.positionCS;
                o.positionWS = vertexInput.positionWS;
                VertexNormalInputs normalInput = GetVertexNormalInputs(v.normalOS, v.tangentOS);
                o.normalWS = normalInput.normalWS;
                o.tangent = normalInput.tangentWS;
                o.bitangent = normalInput.bitangentWS;
                
                o.texcoord = TRANSFORM_TEX(v.texcoord, _BaseMap);
                return o;
            }

            half4 frag(v2f i):SV_Target
            {
                Light light = GetMainLight();
                half3 normalTS = UnpackNormalScale(SAMPLE_TEXTURE2D(_BumpMap, sampler_BumpMap, i.texcoord),_BumpScale);
                half3 normalWS = TransformTangentToWorld(normalTS, half3x3(i.tangent, i.bitangent, i.normalWS));

                half4 albedo = SAMPLE_TEXTURE2D(_BaseMap, sampler_BaseMap, i.texcoord);
                half3 diffuse = _BaseColor.rgb * max(0, dot(normalWS, light.direction)* 0.5+ 0.5)* light.color;
                albedo.rgb *= diffuse;
                return albedo;
            }
            ENDHLSL
        }
    }
}